﻿using CaseManagerLibrary.Auth;
using CaseManagerLibrary.Models;
using CaseManagerLibrary.Socket;
using PSDClientListener.Protocols;
using PSDClientService.SystemSettings;
using PSDLib.Protocols;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PSDClientListener
{
    public class MessageManager
    {
        private ClientListener listener;
        public IPEndPoint TcpServerEP { get; set; }
        public IPEndPoint PSDClientEP { get; set; }
        public TcpManagerAsync tcpManager { get; set; }

        public bool Online { get; set; }

        public MessageManager(ClientListener cl)
        {
            Online = true;
            listener = cl;
        }

        public bool Init()
        {
            bool success = true;

            try
            {
                TcpServerEP = new IPEndPoint(IPAddress.Parse(AppSettings.Setting.TcpServerAddress), AppSettings.Setting.TcpServerPort);
                PSDClientEP = new IPEndPoint(IPAddress.Any, AppSettings.Setting.PSDListenPort);

                var ep = new IPEndPoint(IPAddress.Any, AppSettings.Setting.TcpListenerPort);

                tcpManager = new TcpManagerAsync(ep);
                tcpManager.Received += TcpManager_Received;

                success = true;
            }
            catch (Exception ex)
            {
                success = false;
            }

            return success;
        }

        /// <summary>
        /// 处理消息
        /// </summary>
        /// <param name="text"></param>
        /// <param name="remoteEp"></param>
        private void TcpManager_Received(string text, TcpClientState state)
        {
            try
            {
                MessageBase msg = MessageParser.Parse(text);

                if (msg != null)
                {
                    var processor = ListenerMessageProcessor.Parse(msg);

                    processor?.Run(listener, state);
                }
            }
            catch (Exception ex)
            {
                listener.Logger.Error("处理消息失败：" + ex.Message + " " + text);
            }
        }

        public void Start()
        {
            if (tcpManager != null)
            {
                tcpManager.Start();

                listener.Logger.Info("启动tcp消息服务");
            }
        }

        public void Stop()
        {
            if (tcpManager != null)
            {
                tcpManager.Stop();

                listener.Logger.Info("停止tcp消息服务");
            }
        }

        public HResult Send(IPEndPoint ep, MessageBase message)
        {
            var result = tcpManager.Send(ep, message);

            if (!result.success)
            {
                Online = false;
                listener.Logger.Error("发送消息失败：" + result.message);
            }
            else
            {
                if (!Online)
                {
                    Online = true;
                    listener.Logger.Info("消息服务恢复连接");
                }
            }

            return result;
        }

        public HResult SendToServer(MessageBase message)
        {
            var result = tcpManager.Send(TcpServerEP, message);

            if (!result.success)
            {
                Online = false;
                listener.Logger.Error("发送消息失败：" + result.message);
            }
            else
            {
                if (!Online)
                {
                    Online = true;
                    listener.Logger.Info("消息服务恢复连接");
                }
            }

            return result;
        }
    }
}
